package com.andatsoft.laisim.view;

import java.io.File;

import android.annotation.SuppressLint;
import android.app.WallpaperManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.ViewSwitcher.ViewFactory;

import com.andatsoft.laisim.R;
import com.andatsoft.laisim.activity.MainActivity;
import com.andatsoft.laisim.asynctask.AlbumArtGettingTask;
import com.andatsoft.laisim.db.DataBaseAccess;
import com.andatsoft.laisim.theme.Theme;
import com.andatsoft.laisim.theme.ThemeManager;
import com.andatsoft.laisim.utils.Common;
import com.andatsoft.laisim.utils.ToastMessage;
import com.andatsoft.laisim.utils.Utils;
import com.nineoldandroids.view.ViewHelper;

public class MainAlbumArtFragment extends Fragment {

	private ImageSwitcher mImageSwitcher;
	private WPProgressBar mWPProgress;
	private int mSongId;
	private Point mToolBoxPosition;
	private boolean mIsImageChanged;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.pager_main_album_art, container,
				false);
		mImageSwitcher = (ImageSwitcher) view
				.findViewById(R.id.imgswitcher_pager_main_album_art);
		mWPProgress = (WPProgressBar) view
				.findViewById(R.id.progress_pager_main_album_art_update);
		mImageSwitcher.setFactory(new ViewFactory() {

			@Override
			public View makeView() {
				ImageView img = new ImageView(getActivity()
						.getApplicationContext());
				ImageSwitcher.LayoutParams lp = new ImageSwitcher.LayoutParams(
						ImageSwitcher.LayoutParams.MATCH_PARENT,
						ImageSwitcher.LayoutParams.MATCH_PARENT);
				// lp.gravity = Gravity.CENTER;
				// lp.leftMargin = 20;
				// lp.rightMargin = 20;
				// img.setPadding(6, 4, 8, 9);
				img.setLayoutParams(lp);
				img.setScaleType(ScaleType.FIT_XY);
				return img;
			}

		});
		mImageSwitcher.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if (mToolBoxPosition == null)
					mToolBoxPosition = new Point();
				mToolBoxPosition.x = (int) event.getX();
				mToolBoxPosition.y = (int) event.getY();
				if (mToolBoxPosition.y < v.getHeight() / 3)
					mToolBoxPosition.y += 90;
				return false;
			}
		});
		mImageSwitcher.setOnLongClickListener(new OnLongClickListener() {

			@Override
			public boolean onLongClick(View arg0) {
				mSongId = ((MainActivity) getActivity()).getCurrentSongId();
				Rect r = new Rect();
				mImageSwitcher.getGlobalVisibleRect(r);
				getMainActivity().doLaisimAnimation(mToolBoxPosition.x,
						mToolBoxPosition.y + r.top);
				showToolBox();
				return false;
			}
		});
		updateAnimation(R.anim.fade_in_fast, R.anim.fade_out_fast);
		return view;
	}

	@Override
	public void onResume() {
		super.onResume();
		applyTheme();
	}

	@SuppressLint("NewApi")
	private void applyTheme() {
		Theme theme = ThemeManager.getSelectedTheme();
		if (Utils.androidOs < Common.ANDROID_OS_GINGERBREAD_TO_ICS) {
			ViewHelper.setAlpha(
					((LinearLayout) getMainActivity().findViewById(
							R.id.layout_main_pager_album)),
					theme.getMPAAlhpha());
		} else {
			((LinearLayout) getMainActivity().findViewById(
					R.id.layout_main_pager_album)).setAlpha(theme
					.getMPAAlhpha());
		}
	}

	private MainActivity getMainActivity() {
		return (MainActivity) getActivity();
	}

	private void setBgColor(View v) {
		v.setBackgroundColor(ThemeManager.getSelectedTheme()
				.getDialogBackgroundColor() | 0xff000000);
	}

	@SuppressLint("NewApi")
	protected void setAlpha(View view, float alpha) {
		if (Utils.androidOs > Common.ANDROID_OS_GINGERBREAD) {
			view.setAlpha(alpha);
		} else {
			ViewHelper.setAlpha(view, alpha);
		}
	}

	private void showToolBox() {
		final Toolbox toolBox = getMainActivity().getToolBox();

		if (toolBox == null)
			return;
		toolBox.setContentLayout(R.layout.tool_box_album_art);
		toolBox.show();
		final TextView btnUpdateAlbum = (TextView) toolBox
				.findViewById(R.id.tv_album_art_change);
		btnUpdateAlbum.setTextColor(ThemeManager.getSelectedTheme()
				.getNormalTextColor());
		setBgColor(btnUpdateAlbum);
		btnUpdateAlbum.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					setAlpha(v, 0.5f);
					break;
				case MotionEvent.ACTION_UP:
					setAlpha(v, 1.0f);
					getMainActivity().doLaisimAnimation(v);
					btnUpdateAlbum.setEnabled(false);
					updateAlbumArt(mSongId);
					// root.setVisibility(View.GONE);
					toolBox.close();
					break;
				}
				return true;
			}
		});

		final TextView btnSetAsWallPaper = (TextView) toolBox
				.findViewById(R.id.tv_album_art_set_wallpaper);
		btnSetAsWallPaper.setTextColor(ThemeManager.getSelectedTheme()
				.getNormalTextColor());
		setBgColor(btnSetAsWallPaper);
		btnSetAsWallPaper.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					setAlpha(v, 0.5f);
					break;
				case MotionEvent.ACTION_UP:
					setAlpha(v, 1.0f);
					getMainActivity().doLaisimAnimation(v);
					btnSetAsWallPaper.setEnabled(false);

					new WallPaperTask().execute();

					break;
				}
				return true;
			}
		});

		final TextView btnHideIt = (TextView) toolBox
				.findViewById(R.id.tv_album_art_hide_it);
		final TextView btnRemove = (TextView) toolBox
				.findViewById(R.id.tv_album_art_remove);
		if (getMainActivity().isAlbumArtHidden(mSongId)) {
			btnHideIt.setText(getString(R.string.tool_box_album_art_show_it));
		} else {
			btnHideIt.setText(getString(R.string.tool_box_album_art_hide_it));
		}
		if (!isSongHadAlbumArt(mSongId)) {
			btnHideIt.setVisibility(View.GONE);
			btnRemove.setVisibility(View.GONE);
			btnUpdateAlbum
					.setText(getString(R.string.tool_box_album_art_change));

		} else {
			btnUpdateAlbum
					.setText(getString(R.string.tool_box_album_art_change_to_other));

			btnHideIt.setTextColor(ThemeManager.getSelectedTheme()
					.getNormalTextColor());
			setBgColor(btnHideIt);
			btnHideIt.setOnTouchListener(new OnTouchListener() {

				@Override
				public boolean onTouch(View v, MotionEvent event) {
					switch (event.getAction()) {
					case MotionEvent.ACTION_DOWN:
						setAlpha(v, 0.5f);
						break;
					case MotionEvent.ACTION_UP:
						setAlpha(v, 1.0f);
						getMainActivity().doLaisimAnimation(v);
						btnHideIt.setEnabled(false);
						hideThisAlbumArt(mSongId);
						toolBox.close();
						break;
					}
					return true;
				}
			});

			btnRemove.setTextColor(ThemeManager.getSelectedTheme()
					.getNormalTextColor());
			setBgColor(btnRemove);
			btnRemove.setOnTouchListener(new OnTouchListener() {

				@Override
				public boolean onTouch(View v, MotionEvent event) {
					switch (event.getAction()) {
					case MotionEvent.ACTION_DOWN:
						setAlpha(v, 0.5f);
						break;
					case MotionEvent.ACTION_UP:
						setAlpha(v, 1.0f);
						getMainActivity().doLaisimAnimation(v);
						btnRemove.setEnabled(false);
						removeAlbumArt(mSongId);
						toolBox.close();
						// change to default album art
						setImage(getActivity().getApplicationContext(),
								((BitmapDrawable) ThemeManager
										.getSelectedSkin().getDefaultAlbum())
										.getBitmap());
						getMainActivity().setBackgroundToDefault();
						break;
					}
					return true;
				}
			});
		}

		toolBox.getContent().setPadding(0, mToolBoxPosition.y, 0, 0);
	}

	public boolean isSongHadAlbumArt(int songId) {
		DataBaseAccess db = DataBaseAccess.getInstance(getActivity()
				.getApplicationContext());
		boolean re = db.isAlbumArtExist(songId + "");
		return re;
	}

	public void updateAlbumArt(int songId) {
		new UpdateAlbumTask(getMainActivity().getApplicationContext())
				.execute(songId);
		// Intent i = new Intent(getActivity(), EditLyricsActivity.class);
		// i.putExtra(Common.SONG_ID_INTENT, mSongId);
		// // i.putExtra(Common.SONG_LYRICS_INTENT, mTvLyrics.getText());
		// startActivityForResult(i, Common.REQUEST_CODE_FOR_LYRICS_EDITOR);
	}

	public void hideThisAlbumArt(int songId) {
		if (getMainActivity().isAlbumArtHidden(songId)) {
			// Current is hidden--> show it
			Bitmap bm = BitmapFactory.decodeFile(Environment
					.getExternalStorageDirectory()
					+ "/Laisim/AlbumArt/"
					+ songId);
			setImage(getActivity().getApplicationContext(), bm);
			getMainActivity().setBackgroundBlur(bm, true);
			// update db
			DataBaseAccess db = DataBaseAccess.getInstance(getActivity()
					.getApplicationContext());
			db.setHideAlbumArt(songId, 1);

		} else {
			// Current is shown--> hide it
			// change image to default
			getMainActivity().setBackgroundToDefault();
			setImage(getActivity().getApplicationContext(),
					((BitmapDrawable) ThemeManager.getSelectedSkin()
							.getDefaultAlbum()).getBitmap());
			// update db
			DataBaseAccess db = DataBaseAccess.getInstance(getActivity()
					.getApplicationContext());
			db.setHideAlbumArt(songId, 0);
		}

		// Intent i = new Intent(getActivity(), LyricsGettingDialog.class);
		// i.putExtra(Common.SONG_TITLE_INTENT,
		// ((MainActivity) getActivity()).getCurrentSongTitle());
		// startActivityForResult(i, Common.REQUEST_CODE_FOR_LIST_DIALOG);
	}

	public boolean removeAlbumArt(int songId) {
		// // delete from db
		DataBaseAccess db = DataBaseAccess.getInstance(getActivity()
				.getApplicationContext());
		if (db.deleteAlbumArt(songId) <= 0) {
			return false;
		}

		// delete from File
		File f = new File(Environment.getExternalStorageDirectory()
				+ "/Laisim/AlbumArt/" + songId);
		if (f.exists() && f.isFile()) {
			if (f.delete()) {
				return true;
			}
		}
		return false;
	}

	public Fragment getInstance() {
		return this;
	}

	public ImageSwitcher getImageSwitcher() {
		return mImageSwitcher;
	}

	public void setImage(Context c, Bitmap bm) {
		if (mWPProgress.getVisibility() == View.VISIBLE) {
			mWPProgress.setVisibility(View.GONE);
		}
		mIsImageChanged = true;
		if (c == null)
			return;
		if (bm == null || bm.isRecycled())
			return;
		if (mImageSwitcher == null)
			return;
		mImageSwitcher
				.setImageDrawable(new BitmapDrawable(c.getResources(), bm));
		mIsImageChanged = true;
	}

	public void setBackGround(boolean hasAlbumArt) {
		if (hasAlbumArt) {
			mImageSwitcher.setBackgroundResource(R.drawable.bg_shadow);
		} else {
			mImageSwitcher.setBackgroundResource(0);
		}
	}

	public void updateAnimation(int inId, int outId) {
		if (getActivity() == null)
			return;
		mImageSwitcher.setInAnimation(AnimationUtils.loadAnimation(
				getActivity().getApplicationContext(), inId));
		mImageSwitcher.setOutAnimation(AnimationUtils.loadAnimation(
				getActivity().getApplicationContext(), outId));
	}

	class UpdateAlbumTask extends AlbumArtGettingTask {

		private Bitmap mBitmap;

		public UpdateAlbumTask(Context c) {
			super(c);
		}

		@Override
		protected void onPreExecute() {
			mWPProgress.setVisibility(View.VISIBLE);
			mIsImageChanged = false;
		}

		@Override
		protected Integer doInBackground(Integer... params) {
			int sId = params[0];
			// removeAlbumArt(sId);
			int re = super.doInBackground(params);
			// update new image
			File f = new File(Environment.getExternalStorageDirectory()
					+ "/Laisim/AlbumArt/" + sId);
			if (f.exists() && f.isFile()) {
				mBitmap = BitmapFactory.decodeFile(f.getAbsolutePath());
			}
			return re;

		}

		@Override
		protected void onPostExecute(Integer result) {
			int re = result;
			switch (re) {
			case 0:// setting not allow download
				new ToastMessage(getMainActivity().getApplicationContext())
						.showLongMessage(getString(R.string.toast_auto_download_album_art_not_allowed));
				break;
			case 1:// no wifi available
				new ToastMessage(getMainActivity().getApplicationContext())
						.showLongMessage(getString(R.string.toast_auto_download_album_art_not_allowed_because_of_no_wifi));
				break;
			case 2:// no album art found
				new ToastMessage(getMainActivity().getApplicationContext())
						.showLongMessage(getString(R.string.toast_no_song_album_art_found));
				break;

			}
			if (!mIsImageChanged) {
				mWPProgress.setVisibility(View.GONE);
				if (mBitmap != null) {
					if (getMainActivity() != null) {
						setImage(getMainActivity().getApplicationContext(),
								mBitmap);
						getMainActivity().setBackgroundBlur(mBitmap, true);
					}
				}
			}

		}

	}

	class WallPaperTask extends AsyncTask<Void, Void, Boolean> {

		@Override
		protected void onPreExecute() {
			((WPProgressBar) getMainActivity().getToolBox().findViewById(
					R.id.progress_album_art)).setVisibility(View.VISIBLE);
		}

		@Override
		protected Boolean doInBackground(Void... params) {
			WallpaperManager wp = WallpaperManager.getInstance(getActivity()
					.getApplicationContext());

			try {
				Bitmap bm = getMainActivity().getCurrentAlbumArtBitmap();
				if (bm != null) {

					wp.setBitmap(bm);
					return true;
				}
				return false;
			} catch (Exception e) {
				return false;
			}
		}

		@Override
		protected void onPostExecute(Boolean result) {
			if (getMainActivity() == null)
				return;
			if (getMainActivity().getToolBox() == null)
				return;
			WPProgressBar wp = (WPProgressBar) getMainActivity().getToolBox()
					.findViewById(R.id.progress_album_art);
			if (wp == null)
				return;
			wp.setVisibility(View.INVISIBLE);
			getMainActivity().getToolBox().close();
			if (result != null) {
				if (result) {
					getMainActivity().getToast().showLongMessage(
							getString(R.string.toast_set_wallpaper_ok));
				} else {
					getMainActivity().getToast().showLongMessage(
							getString(R.string.toast_set_wallpaper_failed));
				}
			}
		}

	}

}
